package com.wmm.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.wmm.reggie.common.BaseContext;
import com.wmm.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
@WebFilter(filterName = "LoginCheckFliter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;

        //1.获取本次请求的uri
        String uri = request.getRequestURI();
        //log.info("拦截到"+uri);
        String[] uris = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };
        //2.判断
        boolean check = check(uris, uri);
        //3,不处理，放行
        if (check){
           // log.info("本次请求不需要处理"+uri);
            filterChain.doFilter(request,response);
            return;
        }
        //4.1判断是否登录，如一登陆，放行
        if (request.getSession().getAttribute("employee") != null){
            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(request,response);
            return;
        }
        //4.2判断是否登录，如一登陆，放行
        if (request.getSession().getAttribute("user") != null){

            Long userId = (Long) request.getSession().getAttribute("user");

            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request,response);
            return;
        }
        //5,未登录，输出流相应客户端数据
       // log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return ;
    }


    /**
     * 判断处理是否放行
     * @param uris
     * @param uri
     * @return
     */
    public boolean check(String[] uris,String uri){
        for (String s : uris) {
            boolean match = PATH_MATCHER.match(s, uri);
            if(match){
                return true;
            }
        }
        return false;
    }
}
